package com.example.demo.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        new Thread(new Product(clerk), "生产者A").start();
        new Thread(new Product(clerk), "生产者B").start();
        new Thread(new Consumer(clerk), "消费者A").start();
        new Thread(new Consumer(clerk), "消费者B").start();

    }
}


class Clerk {
    private int product = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void product() {
        lock.lock();
        try {
            while (product >= 1) {
                System.out.println("满货");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + ":" + ++product);
            condition.signalAll();
        } finally {
            //必须记得释放锁
            lock.unlock();
        }

    }

    public void sale() {
        lock.lock();
        try {
            while (product <= 0) {
                System.out.println("缺货");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + ":" + --product);
            condition.signalAll();
        } finally {
            lock.unlock();
        }

    }
}

class Product implements Runnable {
    Clerk clerk;

    public Product(Clerk clerk) {
        this.clerk = clerk;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            clerk.product();
        }
    }
}

class Consumer implements Runnable {
    Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            clerk.sale();
        }
    }
}